package com.hmall.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微服的拦截器
 * 获取请求头中的用户id，存入threadlocal中
 */
public class UserInfoInterceptor implements HandlerInterceptor {
    /**
     * 进入controller前执行
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //微服中如何获取登录用户id
        //通过拦截器(HandlerInterceptor)
        //把请求头中用户id
        String userIdStr = request.getHeader("user-info");
        // 存入trheadlocal
        if(StrUtil.isNotEmpty(userIdStr)){
            UserContext.setUser(Long.parseLong(userIdStr));
        }
        return true;
    }

    /**
     * 调用controller后，无论是否出现异常都会执行
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }
}
